#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/10/21  20:17
# @Author: 余浪人
# @email: yulangren520@gmail.com
import json
from datetime import datetime
from apps.control import sys_bp
from pyecharts.charts import Line
from apps.lib.public import getEveryDay, redis_
from pyecharts import options as opts
from flask_login import login_required
from flask import render_template
from apps.models.order_model import TL_PayOrder_Model


@sys_bp.route('/records_center', endpoint='records_center', methods=['GET'])
@login_required
def records_center():
    return render_template('system_template/chart.html')


@sys_bp.route('/visit_chart', endpoint='visit_chart', methods=['GET'])
@login_required
def visit_user():
    day_s = getEveryDay()
    sub = []
    redis_5 = redis_(db=5)
    for day in day_s:
        data = redis_5.hget('tl_visit_num', day)
        if data: sub.append(json.loads(data))
    begin_day, end_day = datetime.strptime(day_s[0], "%Y-%m-%d"), datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
    dataList = TL_PayOrder_Model.query.filter(TL_PayOrder_Model.send_pay_date >= begin_day, TL_PayOrder_Model.send_pay_date <= end_day).all()
    sub_total = sum([float(data.total_amount) for data in dataList])
    data = {_: 0 for _ in day_s}
    for da in dataList:
        date = datetime.strftime(da.send_pay_date, "%Y-%m-%d")
        data[date] = sum([float(data[date]), float(da.total_amount)])
    c = (
        Line()
            .add_xaxis([day for day in day_s])
            .add_yaxis("用户访问量", [redis_5.hget('tl_visit_num', date) for date in day_s], areastyle_opts=opts.AreaStyleOpts(0.1))
            .add_yaxis("支付宝收益", [v for _, v in data.items()], areastyle_opts=opts.AreaStyleOpts(0.2))
            .set_global_opts(title_opts=opts.TitleOpts(subtitle=f"月访问量: {sum(sub)} /次 | 月收入： %.2f /元" % sub_total))
    )
    return c.dump_options_with_quotes()
